<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      <el-form ref="goods" :model="goodsForm.goods" label-width="120px">
        {{goodsForm}}
        <el-form-item label="商品分类">
          <!--1. 一级分类-->
          <el-select v-model="goodsForm.goods.category1Id" placeholder="请选择一级分类">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in categorys1" :key="cate.id"/>
          </el-select>
          <!--2. 二级分类-->
          <el-select v-model="goodsForm.goods.category2Id" placeholder="请选择二级分类">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in categorys2" :key="cate.id"/>
          </el-select>
          <!--3. 三级分类-->
          <el-select v-model="goodsForm.goods.category3Id" placeholder="请选择三级分类">
            <el-option :label="cate.name" :value="cate.id" v-for="cate in categorys3" :key="cate.id"/>
          </el-select>
          {{goodsForm.goods.typeTemplateId}}
        </el-form-item>

        <el-form-item label="商品名称">
          <el-input v-model="goodsForm.goods.goodsName"/>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="goodsForm.goods.brandId" placeholder="请选择品牌">
            <el-option :label="brand.text" :value="brand.id" v-for="brand in brandList" :key="brand.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="goodsForm.goods.caption"/>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="goodsForm.goods.price"/>
        </el-form-item>
        <el-form-item label="商品介绍">
          <el-input type="textarea" v-model="goodsForm.goodsDesc.introduction"/>
        </el-form-item>
        <el-form-item label="包装列表">
          <el-input type="text" v-model="goodsForm.goodsDesc.packageList"/>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input type="text" v-model="goodsForm.goodsDesc.saleService"/>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="商品图片">
      <el-button type="warning" plain @click="newUpload()">新建</el-button>
      <el-table
        :data="goodsForm.goodsDesc.itemImages"
        style="width: 100%">
        <el-table-column
          label="颜色"
          align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.color }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="图片"
          align="center">
          <template slot-scope="scope">
            <!--<el-image src="scope.row.url" width="100" height="100"></el-image>-->
            <img :src="scope.row.url" width="100px">
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="goodsForm.goodsDesc.itemImages.splice(scope.$index,1)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-table
        :data="goodsForm.goodsDesc.customAttributeItems"
        style="width: 100%">
        <el-table-column
          width="160px"
          align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.text }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.value" placeholder="输入扩展属性"/>
          </template>
        </el-table-column>
      </el-table>

    </el-tab-pane>
    <el-tab-pane label="规格">
      {{optionsList}}
      <el-table
        :data="specificationItems"
        style="width: 100%">
        <el-table-column
          width="100">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionsList[scope.$index]" size="mini">
              <el-checkbox :label="option.optionName" border
                           @change="modifySpec(scope.row.text)"
                           v-for="option in scope.row.options" :value="option.id"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        :data="goodsForm.itemList"
        style="width: 100%">
        <el-table-column
          :label="spec.attributeName"
          v-for="spec in goodsForm.goodsDesc.specificationItems"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.spec[spec.attributeName]}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="价格"
          align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column
          label="库存"
          align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>

      </el-table>
    </el-tab-pane>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="success">返回列表</el-button>
    </div>


    <!--上传图片的对话框-->
    <el-dialog title="上传商品图片" :visible.sync="picDialogVisible">
      {{imageEntity}}
      <el-form :model="imageEntity">
        <el-form-item label="颜色" :label-width="formLabelWidth">
          <el-input v-model="imageEntity.color" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <!--1. 文件上传-->
          <el-upload
            class="upload-demo"
            :file-list="fileList"
            :http-request="uploadFile"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="picDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="picDialogVisible = false">保存</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>

<script>
export default {
  data() {
    return {
      goodsForm: {
        goods: {typeTemplateId: ''},
        goodsDesc: {customAttributeItems: [], itemImages: [], specificationItems: []},
        itemList: []
      },
      categorys1: [],
      categorys2: [],
      categorys3: [],
      brandList: [],
      picDialogVisible: false,
      imageEntity: {},
      formLabelWidth: '100px',
      fileList: [],
      specificationItems: [],
      optionsList: [],     // 选中的规格项数组
      specNames: [],       // 规格名称数组
    }
  },
  // 自动计算属性
  computed: {
    //1. 一级分类的简写
    category1Id() {
      return this.goodsForm.goods.category1Id
    },
    //2. 二级分类的简写
    category2Id() {
      return this.goodsForm.goods.category2Id
    },
    //3. 三级分类的简写
    category3Id() {
      return this.goodsForm.goods.category3Id
    },
    //4. 模板id的简写
    typeTempateId() {
      return this.goodsForm.goods.typeTemplateId
    }
  },
  // 监控某个变量值的变化
  watch: {
    //1. 一级分类的id发生变化，就以这个id为父id来查询其下的所有二级分类列表
    category1Id(newV, oldV) {
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/findByParentId/${newV}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.categorys2 = data.categoryList;
        }
      })
    },
    //2. 二级分类的id发生变化，就以这个id为父id查询其下的所有三级分类列表
    category2Id(newV, oldV) {
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/findByParentId/${newV}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.categorys3 = data.categoryList;
        }
      })
    },
    //3. 三级分类的id发生变化，就可以查询出这个三级分类中的模板id
    category3Id(newV, oldV) {
      this.$http({
        url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("data:", data)
          this.goodsForm.goods.typeTemplateId = data.itemCat.typeId;
        }
      })
    },
    //4. 模板id的值发生变化时，要完成如下几件事件
    typeTempateId(newV, oldV) {
      //4.1 根据模板id查询模板表，从而找到此模板中的对应品牌列表
      // this.goodsForm.itemList = []
      let _this = this
      this.$http({
        url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("data:", data)
          //4.2 得到模板对应的品牌列表
          this.brandList = JSON.parse(data.typeTemplate.brandIds).map(m=>{
            m.id = m.id + ''
            return m
          })
          //4.3 得到模板对应的自定义扩展属性值
          if (!this.$route.query.id) {
            this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
          }
          //4.4 得到对应的规格id列表
          let specIds = JSON.parse(data.typeTemplate.specIds)
          //4.5 根据规格个数确定optionList的个数
          //optionList: 代表在每个规格中选中的元素的值，有几个规格就在optionList这个数组有几个子数组
          if(!_this.$route.query.id)
            specIds.forEach(function () {
              _this.optionsList.push([])
            })


          //4.6 向后端发请求，得到类似：[{"id":27,"text":"网络",OPTIONS:[{},{}]},{"id":32,"text":"机身内存",OPTIONS:[{},{}...]}]
          this.$http({
            url: this.$http.adornUrl(`/shop/specification/findOptionsBySpecId`),
            method: 'post',
            data: specIds,
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.specificationItems = data.specs;
            }

          })
        }

      })
      //4.2 为了避免第二次选择不同的分类，导致模板id的发生变化，这里清空所有的数据
      if(!this.$route.query.id){
        this.clearData()
      }

    }
  },
  activated() {
    //1. 查询一级分类
    this.findCategory1(0)
    //2. 根据商品id查询商品
    this.findById()

  },
  methods: {
    findById() {
      //1. 获取查询参数
      let id = this.$route.query.id;
      console.log("id->>",id)
      //2. 根据商品id查询商品(goods,goodsDesc,item)
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/findById/${id}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("data---->>>",data)
          this.goodsForm = data.goods

          //处理数据
          this.goodsForm.goodsDesc.specificationItems = JSON.parse(this.goodsForm.goodsDesc.specificationItems)
          this.goodsForm.goodsDesc.customAttributeItems = JSON.parse(this.goodsForm.goodsDesc.customAttributeItems)
          this.goodsForm.goodsDesc.itemImages = JSON.parse(this.goodsForm.goodsDesc.itemImages)
          this.goodsForm.itemList.forEach(item => {
            item.spec = JSON.parse(item.spec)
          })
          //让规格选项自动选中

          let items =  this.goodsForm.goodsDesc.specificationItems
          items.forEach((item,index)=>{
            this.optionsList.push(item['attributeValue'])
          })


        }

      })
    },
    clearData() {
      this.specNames = []
      this.optionsList.length = 0
      this.goodsForm.goodsDesc.specificationItems = {}
      this.goodsForm.itemList = [{spec: {}, num: 9999, price: 100, status: 0, isDefault: 0}]
    },
    //1. 保存商品
    save() {
      //1.1 转换要保存到后台的数据
      this.goodsForm.goodsDesc.specificationItems = JSON.stringify(this.goodsForm.goodsDesc.specificationItems)
      this.goodsForm.goodsDesc.itemImages = JSON.stringify(this.goodsForm.goodsDesc.itemImages)
      this.goodsForm.goodsDesc.customAttributeItems = JSON.stringify(this.goodsForm.goodsDesc.customAttributeItems)
      this.goodsForm.itemList = this.goodsForm.itemList.map(item => {
        item.spec = JSON.stringify(item.spec)
        return item
      })
      //1.2 将转换后的数据提交到后台
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/save`),
        method: 'post',
        data: this.goodsForm,
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("data----->", data)

          this.goodsForm = {
            goods: {typeTemplateId: ''},
            goodsDesc: {customAttributeItems: [], itemImages: [], specificationItems: []},
            itemList: []
          }
          // this.clearData()
        }

      })
    },
    //1. 点击了规格选项后
    modifySpec(v) {
      let specItems = []
      //1.1 添加规格名称

      if (!this.specNames.includes(v)) {
        this.specNames.push(v)
      }

      //1.2 将规格名称与optionsList组合新的数据放到: goodsForm.goodsDesc.specificationItems这个数组中
      this.specNames.forEach((spec, index) => {
        specItems.push({"attributeName": spec, "attributeValue": this.optionsList[index]})
      })

      this.goodsForm.goodsDesc.specificationItems = specItems
      //1.3 特殊情况处理，如果attributeValue一项都没有，就将此项从this.goodsForm.goodsDesc.specificationItems中删除它
      this.goodsForm.goodsDesc.specificationItems.forEach((spec, index) => {
        if (spec.attributeValue.length === 0) {
          this.goodsForm.goodsDesc.specificationItems.splice(index, 1)
        }
      })
      //1.4 为sku商品赋值
      this.addSkuList();
    },
    //1.5 为sku商品赋值
    addSkuList() {
      //1.5.1 定义sku商品列表
      this.goodsForm.itemList = [{spec: {}, num: 9999, price: 100, status: 0, isDefault: 0}]
      //1.5.2 得到用户选择的规格及规格选 项列表
      let specItems = this.goodsForm.goodsDesc.specificationItems;
      console.log("specItems--->", specItems)
      //1.5.3 遍历规格选项
      specItems.forEach(spec => {
        this.goodsForm.itemList = this.addColumn(this.goodsForm.itemList, spec.attributeName, spec.attributeValue)
      })

    },
    //1.6 进行深克隆，向this.goodsForm.itemList中添加数据
    addColumn(list, attName, attValue) {
      //1.6.1 声明一个新的数组
      let arr = []
      //1.6.2 遍历list
      list.forEach(item => {
        attValue.forEach(v => {
          //1.6.3 进行深克隆
          let newSku = JSON.parse(JSON.stringify(item))
          //1.6.4 为新对象赋值
          newSku.spec[attName] = v
          //1.6.5 将新对象添加到arr数组中
          arr.push(newSku)
        })
      })

      //1.6.6 返回
      return arr
    },
    newUpload() {
      //1. 打开上传对话框
      this.picDialogVisible = true
      //2. 清空imageEntity
      this.imageEntity = {}
      this.fileList = []
    },
    //0. 文件上传
    uploadFile(v) {
      //0.1 构造一个表单数据对象
      let data = new FormData();
      data.append("file", v.file)
      //0.2 清空文件列表
      this.fileList = []
      //0.2 开始文件上传
      this.$http({
        url: this.$http.adornUrl(`/thirdparty/oss/upload`),
        method: 'post',
        data,
        headers: [{'Content-Type': 'multipart/form-data'}]
      }).then(({data}) => {
        if (data && data.code === 0) {
          //1. 将图片url地址放到imageEntity对象中
          this.imageEntity.url = data.url
          //2. 将上传的文件放到文件列表中
          this.fileList.push({'name': v.raw, 'url': data.url})

          this.goodsForm.goodsDesc.itemImages.push(this.imageEntity)
        }

      })
    },
    //1. 查询一级分类
    findCategory1(parentId) {
      this.$http({
        url: this.$http.adornUrl(`/shop/goods/findByParentId/${parentId}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.categorys1 = data.categoryList;
        }

      })
    }
  }
}
</script>
